import numpy as np
import tensorflow as tf
from PIL import Image
import gradio as gr

# 加载保存的Keras模型
model_path = './mnist_model'
try:
    loaded_model = tf.keras.models.load_model(model_path)
except FileNotFoundError:
    print("无法找到保存的Keras模型文件")
    exit()
except Exception as e:
    print("加载Keras模型时出现错误：", str(e))

# 定义预处理函数
def preprocess(image):
    image = Image.fromarray(image)
    image = image.resize((28, 28)).convert('L')
    image_array = np.array(image)
    normalized_image = image_array / 255.0
    return normalized_image

# 定义预测函数，这个函数将用于Gradio接口进行预测
def predict(image):
    preprocessed_image = preprocess(image)
    preprocessed_image = np.expand_dims(preprocessed_image, axis=0)
    predicted_digit = np.argmax(loaded_model.predict(preprocessed_image))
    return str(predicted_digit)

# 创建Gradio接口，这个接口将用于用户输入和显示预测结果
iface = gr.Interface(fn=predict, inputs='sketchpad', outputs='label')

# 启动Gradio接口，用户可以通过这个接口进行交互
iface.launch()
